package com.baosight.sczx.zm.cm.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiBlock;
import com.baosight.iplat4j.core.ei.EiBlockMeta;
import com.baosight.iplat4j.core.ei.EiColumn;
import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.ef.ui.tree.TreeConstants;
import com.baosight.iplat4j.ef.ui.tree.TreeService;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.cm.MaterialBase;
import com.baosight.sczx.common.zm.cInterface.cm.MaterialType;
import com.baosight.sczx.common.zm.cInterface.cm.TeamMaterialPlanDetail;
import com.baosight.sczx.common.zm.cInterface.cs.InitialData;
import com.baosight.sczx.zm.cm.domain.ZMCMMaterialType;

/**
 * <p>Title: ServiceZMCM01.java</p>
 * <p>Description: 材料基础信息,构造树</p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 杨鸣
 * @version 1.0
 * <pre>Histroy:
 *          2011-05-25 下午15:31:29  杨鸣  Create
 *</pre>
 */

public class ServiceZMCM01 extends TreeService  {

	/**
	 * <p>Function: initLoad</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCM01</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-6-10下午02:49:34 杨鸣
	 * </p>
	 *
	*/
	@Override
	public EiInfo initLoad(EiInfo inInfo) {
		inInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cm.materialClassify"));//材料分类Block 来源于"用户级参数配置"
		return inInfo;
	}


	/**
	 * 系统模块树结构：得到根节点数据
	 * <p>Function: getTopNodes</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCM01</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-05-25 下午15:31:29  杨鸣
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public List getTopNodes() {
		List _topNodes = new ArrayList();

		Map _tempMap = new HashMap<String, String>();
		_tempMap.put("label", "root");
		_tempMap.put("text", "物资分类");		
		_tempMap.put("leaf", "0");

		_tempMap.put("fdKeyId", "root");
		_tempMap.put("fdTypeCode", "root");
		_tempMap.put("fdTypeInnerCode", "root");
		_tempMap.put("fdTypeAllCode", "");
		_tempMap.put("fdTypeName", "物资分类");
		_tempMap.put("fdMaterialClassify", "普通");
		_tempMap.put("fdTypeLevel", "0");	
		_tempMap.put("fdParenttypeCode", "root");	
		_tempMap.put("fdParentId", "root");		
		_tempMap.put("fdIsAddmaterial", "0");
		_topNodes.add(_tempMap);
//-------------------------------------------暂不需"作废分类"节点
//		_tempMap = new HashMap<String, String>();
//
//		_tempMap.put("label", "del");
//		_tempMap.put("text", "作废分类");		
//		_tempMap.put("leaf", "0");
//		
//		_tempMap.put("fdKeyId", "del");
//		_tempMap.put("fdTypeCode", "del");
//		_tempMap.put("fdTypeInnerCode", "del");
//		_tempMap.put("fdTypeName", "作废分类");
//		_tempMap.put("fdMaterialClassify", "普通");
//		_tempMap.put("fdTypeLevel", "0");
//		_tempMap.put("fdParenttypeCode", "del");	
//		_tempMap.put("fdParentId", "del");	
//		_tempMap.put("fdIsAddmaterial", "0");		
//		_topNodes.add(_tempMap);
//-------------------------------------------		
		return _topNodes;
	}


	/**
	 * 系统模块树结构：构造查询树节点的对应子节点
	 * <p>Function: getChildNodes</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCM01</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-5-25下午15:31:29  杨鸣
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public List getChildNodes(String args) {
		Map _argMap = new HashMap();
		_argMap.put(TreeConstants.TREE_NODE, args);  //树节点过滤参数     此树是通过"父类ID"来建立的上下关系

		List childNodes = dao.query("ZMCMMaterialType.treeChildNodes", _argMap);
		return childNodes;
	}


	/**
	 * 叶子列定义
	 * <p>Function: initMetaData</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCM01</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-1-11上午10:11:21 杨鸣
	 * </p>
	 *
	 */
	@Override
	public EiBlockMeta initMetaData() {
		EiBlockMeta eiMetadata = new EiBlockMeta();

		EiColumn eiColumn = new EiColumn("label");
		eiColumn.setDescName("fdKeyId");
		eiColumn.setNullable(false);
		eiColumn.setPrimaryKey(false);
		eiMetadata.addMeta(eiColumn);

		eiColumn = new EiColumn("text");
		eiColumn.setDescName("物资分类");
		eiColumn.setNullable(false);
		eiColumn.setPrimaryKey(false);
		eiMetadata.addMeta(eiColumn);

		eiColumn = new EiColumn("leaf");
		eiColumn.setDescName("是否叶子");
		eiColumn.setType(EiConstant.COLUMN_TYPE_NUMBER);
		eiColumn.setNullable(false);
		eiColumn.setPrimaryKey(false);
		eiMetadata.addMeta(eiColumn);

		eiColumn = new EiColumn("fdKeyId");
		eiColumn.setDescName("fdKeyId");
		eiColumn.setNullable(false);
		eiColumn.setPrimaryKey(false);
		eiMetadata.addMeta(eiColumn);
		
		eiColumn = new EiColumn("fdTypeCode");
		eiColumn.setDescName("类别编码");
		eiColumn.setNullable(false);
		eiColumn.setPrimaryKey(false);
		eiMetadata.addMeta(eiColumn);

		eiColumn = new EiColumn("fdTypeInnerCode");
		eiColumn.setDescName("类别内码");
		eiColumn.setNullable(false);
		eiColumn.setPrimaryKey(false);
		eiMetadata.addMeta(eiColumn);	

		eiColumn = new EiColumn("fdTypeAllCode");
		eiColumn.setDescName("类别全码");
		eiColumn.setNullable(false);
		eiColumn.setPrimaryKey(false);
		eiMetadata.addMeta(eiColumn);
		
		eiColumn = new EiColumn("fdTypeName");
		eiColumn.setDescName("类别名称");
		eiColumn.setNullable(false);
		eiColumn.setPrimaryKey(false);
		eiMetadata.addMeta(eiColumn);

		eiColumn = new EiColumn("fdMaterialClassify");
		eiColumn.setDescName("材料分类");
		eiColumn.setNullable(false);
		eiColumn.setPrimaryKey(false);
		eiMetadata.addMeta(eiColumn);		

		eiColumn = new EiColumn("fdTypeLevel");
		eiColumn.setDescName("类别层级");
		eiColumn.setType(EiConstant.COLUMN_TYPE_NUMBER);
		eiColumn.setNullable(false);
		eiColumn.setPrimaryKey(false);
		eiMetadata.addMeta(eiColumn);
		
		eiColumn = new EiColumn("fdParenttypeCode");
		eiColumn.setDescName("类别父类编码");
		eiColumn.setNullable(false);
		eiColumn.setPrimaryKey(false);
		eiMetadata.addMeta(eiColumn);		

		eiColumn = new EiColumn("fdParentId");
		eiColumn.setDescName("父类编码ID");
		eiColumn.setNullable(false);
		eiColumn.setPrimaryKey(false);
		eiMetadata.addMeta(eiColumn);	
		
		eiColumn = new EiColumn("fdIsAddmaterial");
		eiColumn.setDescName("是否允许加入物资");
		eiColumn.setType(EiConstant.COLUMN_TYPE_NUMBER);
		eiColumn.setNullable(false);
		eiColumn.setPrimaryKey(false);
		eiMetadata.addMeta(eiColumn);
		return eiMetadata;
	}

	/**系统模块：叶子页面数据新增
	 * <p>Function: insert</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCS02</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-1-10上午09:19:33 张小飞
	 * </p>
	 *
	*/
	@Override
	public EiInfo insert(EiInfo inInfo) {
		
		Map<String, String> _map = new HashMap<String, String>();
		
		String fdTypeCode = inInfo.getBlock("result").getCellStr(0, "fdTypeCode");
		String fdParentTypeInnerCode = inInfo.getBlock("result").getCellStr(0, "fdParentTypeInnerCode");
		//为构造类别全码，去掉类别内码中root部分
		String fdParentTypeAllCode = fdParentTypeInnerCode;
		if (fdParentTypeInnerCode.startsWith("root")){
			fdParentTypeAllCode = fdParentTypeInnerCode.substring(4,fdParentTypeInnerCode.length());				
		}
		
		//String fdTypeLevel = inInfo.getBlock("result").getCellStr(0, "fdTypeLevel");
		//String fdParentLevel = inInfo.getBlock("result").getCellStr(0, "fdParentLevel");
		
		//校验序号、编号、名称是否重复
		boolean isRepeat = validate(inInfo, "ZMCMMaterialType.validate", _map);
		
		if(isRepeat) {
			return inInfo;
		}
		else {
			inInfo.getBlock("result").setCell(0, "fdKeyId", TablePk.getInstance().getNextValue("T_CM_MaterialType"));//主键
			//fdTypeInnerCode 默认 父类InnerCODE+本类CODE
			inInfo.getBlock("result").setCell(0, "fdTypeInnerCode",fdParentTypeInnerCode + fdTypeCode);
			inInfo.getBlock("result").setCell(0, "fdTypeAllCode",fdParentTypeAllCode + fdTypeCode);
			//inInfo.getBlock("result").setCell(0, "fdTypeLevel",fdTypeLevel);
			EiInfo outInfo = super.insert(inInfo, "ZMCMMaterialType.insert");
			return outInfo;
		}
	}


	/**
	 * <p>Function: delete</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCM01</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-5-26下午04:50:57 杨鸣
	 * </p>
	 *
	*/
	@Override
	public EiInfo delete(EiInfo inInfo) {
		String fdKeyId = inInfo.getString("fdKeyId");
		String fdTypeInnerCode = inInfo.getString("fdTypeInnerCode");
		Map<String, String> _map = new HashMap<String, String>();
		_map.put("fdKeyId", fdKeyId);
		_map.put("fdTypeInnerCode", fdTypeInnerCode);

		//有无子节点校验
		boolean isHasChildrenType = MaterialType.hasChildrenType(_map, inInfo);
		if(isHasChildrenType) {
			inInfo.setStatus(-1);
			inInfo.setMsg("选中节点下有分类，不能删除该节点！");
			return inInfo;
		}
		else {
			boolean isHasUsedMaterial = MaterialBase.hasUsedMaterial(_map, inInfo);//是否有库存物资
			boolean isHasPlan = TeamMaterialPlanDetail.hasPlan(_map, inInfo);//是否在已经到需求计划
			if(isHasPlan){
				inInfo.setStatus(-1);
				inInfo.setMsg("该类别下的物资已经列入需求计划，不能删除！");
				return inInfo;	
			}else if(isHasUsedMaterial){
				inInfo.setStatus(-1);
				inInfo.setMsg("该类别下的物资有库存数据，不能删除！");
				return inInfo;	
				
			}else{
				
				dao.delete("ZMCMMaterialType.delete", _map);
				dao.update("ZMCMMaterialBasicInfo.modifyUnUseOnDeleteType", _map);
				
				String fdMaterialId = _map.get("fdKeyId");
				_map = new HashMap<String, String>();
				_map.put("fdMaterialId", fdMaterialId);
				dao.delete("ZMCMTypeManageMentSet.delete", _map);
				return inInfo;
			}
		}
	}

	/**
	 * 序号、编号、名称重复验证
	 * <p>Function: validateNo</p>
	 * <p>Description: </p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-1-13下午08:13:00 杨鸣
	 * </p>
	 *
	 */
	@SuppressWarnings("rawtypes")
	private boolean validate(EiInfo inInfo, String sqlName, Map<String, String> params) {
		if(params == null) {
			params = new HashMap<String, String>();
		}
		//String fdTypeName = inInfo.getBlock("result").getCellStr(0, "fdTypeName");
		String fdTypeCode = inInfo.getBlock("result").getCellStr(0, "fdTypeCode");
		String fdKeyId = inInfo.getBlock("result").getCellStr(0, "fdKeyId");
		String fdParentId = inInfo.getBlock("result").getCellStr(0, "fdParentId");

		//params.put("fdTypeName", fdTypeName);
		params.put("fdTypeCode", fdTypeCode);
		params.put("fdParentId", fdParentId);
		
		//编辑时校验需要剔除本记录
		if(!(fdKeyId==null || fdKeyId.equals(""))){
			params.put("fdKeyId", fdKeyId);
		}

		List result = dao.query(sqlName, params);
		if(result!=null && result.size() > 0) {
			inInfo.setStatus(-1);
			ZMCMMaterialType _materialType = (ZMCMMaterialType)result.get(0);
			StringBuffer msg = new StringBuffer("提交失败，");
			if(_materialType.getFdTypeCode() != null && _materialType.getFdTypeCode().equals(fdTypeCode)) {
				msg.append(" 类别编码 ");
			}
			msg.append("重复！");
			inInfo.setMsg(msg.toString());
			return true;
		}
		return false;
	}
	
	/**
	 * 根据ID获得该对象
	 * <p>Function: getMaterialTypeByID</p>
	 * <p>Description: </p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-6-9上午09:50:10 杨鸣
	 * </p>
	 *
	 */
	@SuppressWarnings({ "null", "rawtypes", "unchecked" })
	public EiInfo getMaterialTypeByID(EiInfo inInfo) {
		//先判断根节点是否有值
		List<Map> _list = new ArrayList<Map>();
		_list = dao.query("ZMCMMaterialType.queryRoot",null);
		if(_list.size() == 0)
		{
			EiInfo _inInfo = new EiInfo();
			EiBlock _eiBlock = new EiBlock("result");
			_eiBlock.addBlockMeta(new ZMCMMaterialType().eiMetadata);
			_inInfo.addBlock(_eiBlock);
			_inInfo.getBlock("result").setCell(0, "fdKeyId", "root");
			_inInfo.getBlock("result").setCell(0, "fdTypeCode", "root");
			_inInfo.getBlock("result").setCell(0, "fdTypeInnerCode", "root");
			_inInfo.getBlock("result").setCell(0, "fdTypeAllCode", "root");
			_inInfo.getBlock("result").setCell(0, "fdTypeName", "物资分类");
			_inInfo.getBlock("result").setCell(0, "fdMaterialClassify", "普通");
			_inInfo.getBlock("result").setCell(0, "fdTypeLevel", 0);
			_inInfo.getBlock("result").setCell(0, "fdParentId", "self");
			_inInfo.getBlock("result").setCell(0, "fdIsAddmaterial", 0);
			super.insert(_inInfo, "ZMCMMaterialType.insert");
		}
		
		StaticTools.setQueryParameters(inInfo, "fdKeyId", inInfo.getString("fdKeyId"), true);
		EiInfo outInfo = super.query(inInfo, "ZMCMMaterialType.query", new ZMCMMaterialType());
		String fdParentTypeCode = outInfo.getBlock("result").getCellStr(0, "fdParentTypeCode");
		String fdParentTypeName = outInfo.getBlock("result").getCellStr(0, "fdParentTypeName");
		String fdParentTypeInnerCode = outInfo.getBlock("result").getCellStr(0, "fdParentTypeInnerCode");
		
		if(fdParentTypeCode == null && fdParentTypeCode.length() == 0) {
			outInfo.getBlock("result").setCell(0, "fdParentTypeCode","root");
		}
		if(fdParentTypeName == null && fdParentTypeName.length() == 0) {
			outInfo.getBlock("result").setCell(0, "fdParentTypeName","物资分类");
		}
		if(fdParentTypeInnerCode == null && fdParentTypeInnerCode.length() == 0) {
			outInfo.getBlock("result").setCell(0, "fdParentTypeInnerCode","root");
		}		

		return outInfo;
		
		
	}
	/**
	 * 
	 * <p>Function: update</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCM01</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-6-9上午11:25:57 杨鸣
	 * </p>
	 *
	 */
	@Override
	public EiInfo update(EiInfo inInfo) {
		Map<String, String> params = new HashMap<String, String>();
		
        //已改为在validate中得到EiInfo数据，此处不需要
//		params.put("fdKeyId", inInfo.getBlock("result").getCellStr(0, "fdKeyId"));
		
		//校验序号、编号、名称是否重复
		boolean isRepeat = validate(inInfo, "ZMCMMaterialType.validate", params);
		if(isRepeat) {
			return inInfo;
		}
		else {
			//此处：“如果该分类下已存在物资资料，该分类下允许加入物资资料未勾选，则提示用户该分类下已有物资，请先删除物资，再修改分类信息。”这样的判断已经去除
//			String fdIsAddmaterial = inInfo.getBlock("result").getCellStr(0, "fdIsAddmaterial");
//			String fdKeyId = inInfo.getBlock("result").getCellStr(0, "fdKeyId");
//			if("0".equals(fdIsAddmaterial)){
//				StaticTools.setQueryParameters(inInfo, "fdParentId", fdKeyId, true);
//				EiInfo typeInfo = super.query(inInfo, "ZMCMMaterialType.queryChildren", new ZMCMMaterialType());
//				List typeIds = new ArrayList();
//				for(int i = 0; i < typeInfo.getBlock("result").getRowCount(); i++){
//					typeIds.add(typeInfo.getBlock("result").getCellStr(i, "fdKeyId"));
//				}
//				
//				StaticTools.setQueryParameters(inInfo, "fdMaterialTypeIds", typeIds, true);
//				EiInfo basicInfo = super.query(inInfo, "ZMCMMaterialBasicInfo.hasBasicInfo", new ZMCMMaterialBasicInfo());
//				if(basicInfo.getBlock("result").getRowCount() > 0){
//					basicInfo.setStatus(-1);
//					basicInfo.setMsg("该分类下已有物资，请先删除物资，再修改分类信息！");
//					return basicInfo;
//				}
//			}
			
			EiInfo outInfo = super.update(inInfo, "ZMCMMaterialType.update");
			return outInfo;
		}
	}
	
}
